<template>
    <div>
        <h2>部门管理</h2>

        <!-- 搜索区域 -->
        <div class="search-container">
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="部门名称">
                    <el-input v-model="searchForm.name" placeholder="请输入部门名称" clearable style="width: 200px" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 200px">
                        <el-option label="启用" :value="1" />
                        <el-option label="禁用" :value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
            <el-button type="primary" :icon="Plus" @click="openAddDialog">
                添加部门
            </el-button>
            <el-button type="danger" :icon="Delete" @click="batchDeleteDepartments"
                :disabled="!storedSelectedIds.length">
                一键删除 ({{ storedSelectedIds.length }})
            </el-button>
        </div>

        <!-- 部门表格 -->
        <div class="department-management">
            <el-table v-loading="loading" :data="departments" class="data-table" stripe row-key="id"
                @select="handleSelect" @select-all="handleSelectAll" ref="departmentTableRef">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="name" label="部门名称" width="220" />
                <el-table-column label="父部门" width="180">
                    <template #default="{ row }">
                        {{ row.parentId === "0" ? '无' : getDepartmentName(row.parentId) }}
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="150">
                    <template #default="{ row }">
                        <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                            {{ row.status === 1 ? '启用' : '禁用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="部门描述" />
                <el-table-column label="操作" width="280">
                    <template #default="{ row }">
                        <el-button type="primary" :icon="EditPen" circle @click="editDepartment(row)" />
                        <el-button type="danger" :icon="Delete" circle @click="handleDeleteDepartment(row)" />
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :page-sizes="pageSizes" :small="false" :background="true"
                    layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>

            <!-- 已选部门信息 -->
            <div v-if="storedSelectedIds.length" class="selected-info">
                已选择 {{ storedSelectedIds.length }} 个部门:
                <el-tag v-for="id in storedSelectedIds" :key="id" type="info" closable
                    @close="handleRemoveSelectedById(id)">
                    {{ getDepartmentById(id)?.name || '未知部门' }}
                </el-tag>
            </div>
        </div>

        <!-- 添加/编辑部门对话框 -->
        <el-dialog v-model="dialogVisible" :title="form.id ? '修改部门' : '添加部门'" width="50%" @close="handleDialogClose">
            <el-form :model="form" label-width="80px">
                <el-form-item label="部门名称" required>
                    <el-input v-model="form.name" placeholder="请输入部门名称" />
                </el-form-item>
                <el-form-item label="父部门">
                    <el-select v-model="form.parentId" placeholder="请选择父部门" clearable>
                        <el-option label="初始部门" :value="0" />
                        <el-option v-for="dept in allDepartmentOptions" :key="dept.value" :label="dept.label"
                            :value="dept.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="form.status">
                        <el-radio :label="1">启用</el-radio>
                        <el-radio :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="部门描述">
                    <el-input v-model="form.description" type="textarea" :rows="3" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import { Plus, EditPen, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onBeforeRouteLeave } from 'vue-router'
import {
    fetchDepartments,
    addDepartment,
    deleteDepartment,
    updateDepartment
} from '@/api/department'

// 响应式数据
const departments = ref([])
const departmentTableRef = ref(null)
const selectedDepartments = ref([])
const storedSelectedIds = ref([])
const departmentOptions = ref([])
const loading = ref(false)
const dialogVisible = ref(false)

// 表单数据
const form = ref({
    id: null,
    name: '',
    parentId: '',
    status: 1,
    description: ''
})

// 临时表单数据（用于保存未提交的表单）
const tempForm = ref({
    name: '',
    parentId: '',
    status: 1,
    description: ''
})

// 搜索表单
const searchForm = ref({
    name: '',
    status: null
})

// 分页数据
const pagination = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0
})

const pageSizes = [5, 10, 20, 50, 100]

// 部门ID到名称的映射
const deptIdToName = ref({})

// 加载选中ID
const loadSelectedIds = () => {
    const saved = localStorage.getItem('selectedDepartmentIds')
    if (saved) {
        storedSelectedIds.value = JSON.parse(saved)
    }
}

// 保存选中ID
const saveSelectedIds = () => {
    localStorage.setItem('selectedDepartmentIds', JSON.stringify(storedSelectedIds.value))
}

// 页面离开时保存状态
onBeforeRouteLeave((to, from, next) => {
    localStorage.setItem('tempDepartmentForm', JSON.stringify(tempForm.value))
    saveSelectedIds()
    next()
})

// 恢复选中状态
const restoreSelection = () => {
    if (!departmentTableRef.value || !departments.value.length) return

    departmentTableRef.value.clearSelection()

    // 选中当前页中已存储的部门
    departments.value.forEach(dept => {
        if (storedSelectedIds.value.includes(dept.id)) {
            departmentTableRef.value.toggleRowSelection(dept, true)
        }
    })

    // 更新当前页选中部门
    selectedDepartments.value = departments.value.filter(dept =>
        storedSelectedIds.value.includes(dept.id)
    )
}

// 单选处理
const handleSelect = (selection, row) => {
    const isSelected = selection.some(item => item.id === row.id)

    if (isSelected) {
        if (!storedSelectedIds.value.includes(row.id)) {
            storedSelectedIds.value.push(row.id)
        }
    } else {
        storedSelectedIds.value = storedSelectedIds.value.filter(id => id !== row.id)
    }

    // 更新当前页选中部门
    selectedDepartments.value = selection
    saveSelectedIds()
}

// 全选处理
const handleSelectAll = (selection) => {
    if (selection.length === 0) {
        // 取消全选 - 只移除当前页部门的选中状态
        departments.value.forEach(dept => {
            storedSelectedIds.value = storedSelectedIds.value.filter(id => id !== dept.id)
        })
    } else {
        // 全选 - 添加当前页所有部门的选中状态
        departments.value.forEach(dept => {
            if (!storedSelectedIds.value.includes(dept.id)) {
                storedSelectedIds.value.push(dept.id)
            }
        })
    }

    selectedDepartments.value = selection
    saveSelectedIds()
}

// 同步选中状态
const syncSelectionState = () => {
    nextTick(() => {
        if (!departmentTableRef.value || !departments.value.length) return

        // 获取当前所有选中行
        const currentSelected = departmentTableRef.value.selection || []
        const currentSelectedIds = currentSelected.map(d => d.id)

        // 应该选中的ID
        const shouldSelectedIds = storedSelectedIds.value

        // 同步选中状态
        departments.value.forEach(dept => {
            const shouldSelect = shouldSelectedIds.includes(dept.id)
            const isSelected = currentSelectedIds.includes(dept.id)

            if (shouldSelect && !isSelected) {
                departmentTableRef.value.toggleRowSelection(dept, true)
            } else if (!shouldSelect && isSelected) {
                departmentTableRef.value.toggleRowSelection(dept, false)
            }
        })
    })
}

// 通过ID移除选中部门
const handleRemoveSelectedById = (id) => {
    // 从存储中移除
    storedSelectedIds.value = storedSelectedIds.value.filter(storedId => storedId !== id)

    // 如果部门在当前页，更新表格选中状态
    const deptInPage = departments.value.find(dept => dept.id === id)
    if (deptInPage) {
        departmentTableRef.value?.toggleRowSelection(deptInPage, false)
        selectedDepartments.value = selectedDepartments.value.filter(d => d.id !== id)
    }

    saveSelectedIds()
}

// 批量删除部门
const batchDeleteDepartments = async () => {
    if (!storedSelectedIds.value.length) {
        ElMessage.warning('请先选择要删除的部门')
        return
    }

    try {
        await ElMessageBox.confirm(
            `确定删除选中的 ${storedSelectedIds.value.length} 个部门吗?`,
            '批量删除确认',
            { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
        )

        await Promise.all(storedSelectedIds.value.map(id =>
            deleteDepartment(id)
        ))

        storedSelectedIds.value = []
        selectedDepartments.value = []
        saveSelectedIds()
        ElMessage.success('批量删除成功')
        await getDepartments()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量删除失败:', error)
            ElMessage.error('批量删除失败')
        }
    }
}

// 编辑部门
const editDepartment = (department) => {
    form.value = {
        ...department,
        parentId: department.parentId === null ? 0 : department.parentId // 将null转换为0
    }
    dialogVisible.value = true
}

// 打开添加对话框
const openAddDialog = () => {
    form.value = {
        id: null,
        name: tempForm.value.name,
        parentId: tempForm.value.parentId,
        status: tempForm.value.status,
        description: tempForm.value.description
    }
    dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
    if (!form.value.name) {
        ElMessage.warning('请填写部门名称')
        return
    }

    const submitData = {
        ...form.value,
        parentId: form.value.parentId === 0 ? null : form.value.parentId // 将0转换回null
    }

    try {
        if (form.value.id) {
            await updateDepartment(submitData)
            ElMessage.success('修改部门成功')
        } else {
            await addDepartment(submitData)
            ElMessage.success('添加部门成功')
            // 如果是添加操作，清空tempForm
            tempForm.value = {
                name: '',
                parentId: '',
                status: 1,
                description: ''
            }
            form.value = {
                name:'',
                parent:'',
                status:1,
                description:''
            }
        }
        dialogVisible.value = false
        await getDepartments()
    } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message))
    }
}

// 对话框关闭时处理
const handleDialogClose = () => {
    // 如果是添加操作且未提交，保存当前表单数据到tempForm
    if (!form.value.id) {
        tempForm.value = {
            name: form.value.name,
            parentId: form.value.parentId,
            status: form.value.status,
            description: form.value.description
        }
    }
    // 重置表单
    form.value = {
        id: null,
        name: '',
        parentId: '',
        status: 1,
        description: ''
    }
}

// 删除单个部门
const handleDeleteDepartment = async (department) => {
    try {
        await ElMessageBox.confirm(
            `确定删除 ${department.name} 部门吗?`,
            '删除确认',
            { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
        )

        await deleteDepartment(department.id)

        // 1. 从主列表中移除
        departments.value = departments.value.filter(d => d.id !== department.id)

        // 2. 如果该部门是被选中的，从选中列表中移除
        if (selectedDepartments.value.some(d => d.id === department.id)) {
            selectedDepartments.value = selectedDepartments.value.filter(d => d.id !== department.id)
            storedSelectedIds.value = storedSelectedIds.value.filter(id => id !== department.id)
        }

        // 3. 无论是否选中，都同步表格状态
        nextTick(() => {
            // 确保从表格中移除选中状态
            departmentTableRef.value?.toggleRowSelection(department, false)

            // 完全同步选中状态
            syncSelectionState()
        })

        ElMessage.success('部门删除成功')
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
            ElMessage.error('部门删除失败')
        }
    }
}

// 获取部门列表
const getDepartments = async (params = {}) => {
    loading.value = true
    try {
        const response = await fetchDepartments({
            page: pagination.value.currentPage,
            size: pagination.value.pageSize,
            ...params  // 使用传入的搜索参数
        })

        if (response.data.code === 200) {
            departments.value = response.data.data.departments
            pagination.value.total = response.data.data.total

            // 只构建当前页的部门选项，不再构建映射关系
            departmentOptions.value = flattenDepartments(response.data.data.departments)

            nextTick(() => {
                restoreSelection()
            })
        }
    } catch (error) {
        console.error('获取部门列表失败:', error)
        ElMessage.error('获取部门数据失败')
    } finally {
        loading.value = false
    }
}

// 递归构建部门ID到名称的映射
const buildDeptMap = (departments) => {
    deptIdToName.value = {}
    const buildMap = (nodes) => {
        nodes.forEach(node => {
            deptIdToName.value[node.id] = node.name
            if (node.children && node.children.length) {
                buildMap(node.children)
            }
        })
    }
    buildMap(departments)
}

// 将树形数据扁平化
const flattenDepartments = (departments) => {
    const result = []
    const flatten = (nodes) => {
        nodes.forEach(node => {
            result.push({
                value: node.id,
                label: node.name
            })
            if (node.children && node.children.length) {
                flatten(node.children)
            }
        })
    }
    flatten(departments)
    return result
}

// 根据ID获取部门名称
const getDepartmentName = (id) => {
    return deptIdToName.value[id] || '初始部门'
}

// 根据ID获取部门对象
const getDepartmentById = (id) => {
    const deptInPage = departments.value.find(dept => dept.id === id)
    if (deptInPage) return deptInPage
    return null
}

// 重置搜索
const resetSearch = () => {
    searchForm.value = {
        name: '',
        status: null
    }
    pagination.value.currentPage = 1
    getDepartments()
}

// 搜索方法
const handleSearch = () => {
    pagination.value.currentPage = 1

    const searchParams = {
        name: searchForm.value.name || undefined,
        status: searchForm.value.status !== null ? searchForm.value.status : undefined
    }

    const filteredParams = Object.fromEntries(
        Object.entries(searchParams).filter(([_, v]) => v !== undefined
        ))

    getDepartments(filteredParams)
}

// 分页变化处理
const handleSizeChange = (val) => {
    pagination.value.pageSize = val
    pagination.value.currentPage = 1
    getDepartments()
}

const handleCurrentChange = (val) => {
    pagination.value.currentPage = val
    getDepartments()
}

// 新增一个响应式变量用于存储所有部门选项
const allDepartmentOptions = ref([])

// 修改getAllDepartments函数
const getAllDepartments = async () => {
    try {
        const response = await fetchDepartments({
            page: 1,
            size: 10000 // 获取足够大的数量确保拿到所有部门
        })
        if (response.data.code === 200) {
            // 保存所有部门选项
            allDepartmentOptions.value = flattenDepartments(response.data.data.departments)
            // 构建完整的部门映射关系
            buildDeptMap(response.data.data.departments)
        }
    } catch (error) {
        console.error('获取完整部门列表失败:', error)
    }
}

// 在初始化时调用
onMounted(() => {
    // 从本地存储加载临时表单数据
    const savedForm = localStorage.getItem('tempDepartmentForm')
    if (savedForm) {
        tempForm.value = JSON.parse(savedForm)
    }
    
    loadSelectedIds()
    getAllDepartments()
    getDepartments()
})
</script>

<style scoped>
.page-container {
    padding: 20px;
}

.search-container {
    margin-bottom: 20px;
}

.action-buttons {
    margin-bottom: 20px;
}

.department-management {
    background: white;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.data-table {
    width: 100%;
    margin-bottom: 20px;
}

.selected-info {
    margin-top: 15px;
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
}

.selected-info .el-tag {
    margin-right: 8px;
    margin-bottom: 8px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
</style>